package com.corecloud.config.mobile;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * 该类对应普通登陆的 UsernamePasswordAuthenticationToken
 * @author
 * @description
 *  该类继承自 AbstractAuthenticationToken，在 AbstractAuthenticationToken 能看到实现了 Authentication 接口，
 *  而 Authentication 是封装了登录时的认证信息。
 */
public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {
    private static final long serialVersionUID = 500L;

    /**
     * 手机号
     */
    private final Object principal;

    /**
     * SmsCodeAuthenticationFilter 中构建的未认证的 Authentication
     * @param mobile
     */
    public SmsCodeAuthenticationToken(Object mobile) {
        /*传到父类的权限集合是null
        * 其中 super((Collection)null); 点进去，
        * 可以看到是AbstractAuthenticationToken的构造方法，参数authorities是权限的集合，
        * 由于调用的时候不知道权限信息，所以传入的authorities是空的。*/
        super((Collection)null);
        this.principal = mobile;
//        所以 this.setAuthenticated(false); 即没有通过身份认证。
        this.setAuthenticated(false);
    }

    /**
     * SmsCodeAuthenticationProvider 中构建已认证的 Authentication
     * @param principal
     * @param authorities
     */
    public SmsCodeAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        super.setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    /**
     * @param isAuthenticated
     * @throws IllegalArgumentException
     */
    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        } else {
            super.setAuthenticated(false);
        }
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }
}
